package com.hcmiu.buddytracking;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import Constant.Constant;
import Parser.StringtoMD5;
import Utils.toastMaking;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class Login extends Activity {
	private static final String login_URL = Constant.loginServlet;

	private ProgressDialog progressDialog;
	private EditText UserEditText;
	private EditText PassEditText;
	private static final String PREF_NAME = "buddytracking";

	private SharedPreferences pref;
	private String currentPhoneNumber;
	private String password;
	private boolean boxChecked;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);

		progressDialog = new ProgressDialog(this);
		progressDialog.setMessage("Please wait...");
		progressDialog.setIndeterminate(true);
		progressDialog.setCancelable(false);

		UserEditText = (EditText) findViewById(R.id.username);
		PassEditText = (EditText) findViewById(R.id.password);
		UserEditText.setHint("Tap to enter phonenumber");
		PassEditText.setHint("Tap to enter password");
		Button button = (Button) findViewById(R.id.okLoginButton);
		CheckBox checkbox = (CheckBox) findViewById(R.id.loginCheckBox);
		// remember me
		pref = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
		currentPhoneNumber = pref.getString("currentPhoneNumber", null);
		password = pref.getString("password", null);
		boxChecked = (pref.getBoolean("BoxChecked", false));
		// prepare for login
		if (currentPhoneNumber != null && password != null
				&& boxChecked == true) {
			UserEditText.setText(currentPhoneNumber);
			PassEditText.setText(password);
			checkbox.setChecked(true);
		}
		else
		{
			UserEditText.setText(null);
			PassEditText.setText(null);
		}
		checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if (boxChecked == true)
					boxChecked = false;
				else if (boxChecked == false)
					boxChecked = true;
			}
		});
		button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				int usersize = UserEditText.getText().length();
				int passsize = PassEditText.getText().length();
				if (usersize > 0 && passsize > 0) {
					progressDialog.show();
					// progressDialog.incrementProgressBy(1);
					String user = UserEditText.getText().toString();
					String pass = PassEditText.getText().toString();
					doLogin(user, pass);

				} else
					toastMaking.errorToast(getApplicationContext(),
							"Enter phone number and Password").show();
			}
		});

		button = (Button) findViewById(R.id.cancelLoginButton);
		button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Login.this.finish();
			}
		});
	}

	private void doLogin(final String login, final String pass) {
		Thread t = new Thread() {
			@Override
			public void run() {
				Looper.prepare();
				DefaultHttpClient client = new DefaultHttpClient();
				HttpConnectionParams.setConnectionTimeout(client.getParams(),
						15000);
				HttpResponse response;
				HttpEntity entity;
				try {

					// ////////////////////////////
					// JSON
					JSONObject obj = new JSONObject();
					obj.put("name", login);
					obj.put("pass", StringtoMD5.MD5(pass));
					String jsonText = obj.toString();

					// /////////////////////////
					HttpPost post = new HttpPost(login_URL);
					List<NameValuePair> nvps = new ArrayList<NameValuePair>();
					nvps.add(new BasicNameValuePair("jsonText", jsonText));
					post.setHeader("Content-Type",
							"application/x-www-form-urlencoded");
					post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
					response = client.execute(post);
					entity = response.getEntity();
					String result = EntityUtils.toString(entity);
					if (result.equals("1")) {
						progressDialog.dismiss();
						getSharedPreferences(PREF_NAME, MODE_PRIVATE).edit()
								.putString("currentPhoneNumber", login)
								.putString("password", pass).putBoolean(
										"BoxChecked", boxChecked).commit();
						Intent i = new Intent(Login.this, Map.class);
						toastMaking.infoToast(getApplicationContext(),
								"Connection established...").show();
						startActivity(i);
						Login.this.finish();
					} else if (result.equals("2")) {
						progressDialog.dismiss();
						toastMaking.errorToast(getApplicationContext(),
								"Someone is using this account").show();
					} else if (result.equals("3")) {
						progressDialog.dismiss();
						toastMaking.errorToast(getApplicationContext(),
								"Your account is inactive").show();
					} else if (result.equals("0")) {
						progressDialog.dismiss();
						toastMaking.errorToast(getApplicationContext(),
								"Login details are not correct").show();
					} else {
						progressDialog.dismiss();
						toastMaking
								.errorToast(getApplicationContext(),
										"Internal server error, please try again later")
								.show();
					}
					if (entity != null)
						entity.consumeContent();
				} catch (Exception e) {
					progressDialog.dismiss();
					toastMaking.errorToast(getApplicationContext(),
							"Could not establish connetion").show();
				}
				Looper.loop();
			}
		};
		t.start();
	}

}